﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoShopping.Utility.EnumBoundings
{
    /// <summary>
    /// 枚举操作类
    /// </summary>
    public class OptionEnum
    {
        /// <summary>
        /// 返回可以绑定的枚举对象列表
        /// </summary>
        /// <example>
        /// 使用示例：
        /// YourComboBoxControl.DataSource = list;
        /// YourComboBoxControl.DisplayMember = "Name";
        /// YourComboBoxControl.ValueMember = "Value";
        /// </example>
        /// <param name="t">typeof(YourEnumClassName)</param>
        /// <returns></returns>
        public static IList<ComboBoxItem> GetEnumNameValueKeys(Type t)
        {
            EnumDescConverter enumdescconverter = new EnumDescConverter(t);
            string[] names = Enum.GetNames(t);
            int[] values = (int[])Enum.GetValues(t);

            List<ComboBoxItem> list = new List<ComboBoxItem>();
            for (int i = 0; i < names.Length; i++)
            {
                list.Add(new ComboBoxItem((string)enumdescconverter.ConvertTo(names[i], typeof(string)), names[i], values[i]));
            }
            return list;
        }

        /// <summary>
        /// 取出枚举的Description
        /// </summary>
        /// <param name="t"></param>
        /// <param name="enumValueKey"></param>
        /// <returns></returns>
        public static string GetEnumDescription(Type t, string enumValueKey)
        {
            List<ComboBoxItem> list = (List<ComboBoxItem>)GetEnumNameValueKeys(t);
            list = list.FindAll(delegate(ComboBoxItem s) { return s.Value == enumValueKey; });
            if (list.Count == 1)
            {
                return list[0].Name;
            }
            else
            {
                return null;
            }
        }
    }
}
